import React from "react";
import { Checkbox } from "antd";
import {deepCopy, messages} from "share/common";

class CheckboxGroupAll extends React.Component {

  state = {
    value: []
  };

  componentDidMount() {
    if('value' in this.props) {
      const { value, options, entityType } = this.props;
      let initialValue = value ? value.concat([]) : [];
      if(options.length === value.length) {
        initialValue.push('_ALL');
      }
      this.setState({ value: initialValue, entityType });
    }
  }

  componentWillReceiveProps(nextProps) {
    if('value' in nextProps) {
      const { value, options } = nextProps;
      let nextValue = value ? value.concat([]) : [];
      if(options.length === value.length) {
        nextValue.push('_ALL');
      }
      this.setState({ value: nextValue });
    }
    if(nextProps.entityType !== this.state.entityType) {
      this.setState({ value: [], entityType: nextProps.entityType });
    }
  }

  onCheck = checkedList => {
    const { value } = this.state;
    const { options } = this.props;
    let nextValue = [];
    if(checkedList.indexOf("_ALL") > -1 && value.indexOf('_ALL') === -1)
      nextValue = ['_ALL'].concat(options.map(i => i.value));
    if(checkedList.indexOf("_ALL") === -1 && value.indexOf('_ALL') > -1)
      nextValue = [];
    if(checkedList.indexOf("_ALL") === -1 && value.indexOf('_ALL') === -1)
      nextValue = checkedList;
    if(checkedList.indexOf("_ALL") > -1 && value.indexOf('_ALL') > -1) {
      checkedList.delete('_ALL');
      nextValue = checkedList;
    }

    this.setState({ value: nextValue },  this.dispatchOnChange);
  };

  dispatchOnChange = () => {
    const { onChange } = this.props;
    const { value } = this.state;
    onChange && onChange(value.concat([]));
  };

  render () {
    const { options } = this.props;
    const { value } = this.state;
    let optionsCopy = deepCopy(options);
    if(options.length > 1){
      optionsCopy = [{
        label: messages('common.all')/*全部*/,
        value: '_ALL'
      }].concat(options);
    }
    return <Checkbox.Group options={optionsCopy} value={value} onChange={this.onCheck}/>

  }

}
export default CheckboxGroupAll;
